package com.briup.corejava.day20;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

/**
 * TCP协议下的客户端
 */
public class TcpClient {
    public static void main(String[] args) {
        // 获取输入
        Scanner sc = new Scanner(System.in);
        System.out.println("账号：");
        String username = sc.next();
        System.out.println("密码：");
        String password = sc.next();
        // 根据输入的信息，构建对象
        User user = new User(username, password);
        // 创建一个Socket访问指定服务（ip+端口）
        Socket socket = null;
        String ip = "127.0.0.1";
        int port = 8888;
        try {
            socket = new Socket(ip,port);
            System.out.println("访问"+ip+":"+port+"下的资源");
            // 使用输出流向socket写入数据
            ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
            oos.writeObject(user);
            oos.flush();

            System.out.println("正在登录中...");

            BufferedReader br = new BufferedReader(
                    new InputStreamReader(
                            socket.getInputStream()
                    )
            );
            String s = br.readLine();
            System.out.println("服务器的返回结果为："+s);

            System.out.println("请求服务器返回用户的详细信息");
            oos.writeObject("标识");

        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            if(socket!=null){
                try {
                    socket.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
